package com.chenglu.android.search;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseActionBarActivity;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.index.bean.IndexRecomBean;
import com.chenglu.android.search.adapter.SearchAdapter;
import com.chenglu.android.search.mvp.contract.SearchContract;
import com.chenglu.android.search.mvp.presenter.SearchPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023/10/22 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：搜索结果
 */
public class SearchResultActivity extends BaseActionBarActivity<SearchPresenter> implements SearchContract.View {
    public static final String SEARCHNAME = "SEARCHNAME";

    public static final String SHOPSTYPEID = "shopsTypeId";

    public static final String CATEGORYID = "categoryId";

    public static final String TYPESHOP = "typeShop";

    @BindView(R.id.tv_ruby_synthesize)
    TextView tvRubySynthesize;
    @BindView(R.id.tv_sell_number)
    TextView tvSellNumber;
    @BindView(R.id.rt_ruby_sell)
    RelativeLayout rtRubySell;
    @BindView(R.id.tv_ruby_price)
    TextView tvRubyPrice;
    @BindView(R.id.iv_ruby_price)
    ImageView ivRubyPrice;
    @BindView(R.id.rt_ruby_price)
    RelativeLayout rtRubyPrice;
    @BindView(R.id.tv_ruby_newsale)
    TextView tvRubyNewsale;
    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;


    private SearchAdapter searchAdapter;
    private int current = 1;

    private String priceSort; //价格排序，由高往低传asc，由低往高传des 默认不传

    private String salesAmountSort; //销量排序，由高往低传asc，由低往高传desc 默认不传

    private String createTimeSort; //新品排序，由高往低传asc，由低往高传desc 默认不传

    //判断三种状态 综合推荐 红豆 价格
    private int state = 0;

    //搜索名字和方法
    private String searchname;

    private String shopsTypeId;

    private String categoryId;

    //商超传过来的分类id
    int typeShop;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected void initView() {

        mPresenter = new SearchPresenter();
        mPresenter.attachView(this);
        searchname = getIntent().getStringExtra(SEARCHNAME);

        shopsTypeId = getIntent().getStringExtra(SHOPSTYPEID);

        categoryId = getIntent().getStringExtra(CATEGORYID);

        typeShop = getIntent().getIntExtra(TYPESHOP,0);

        setCenterText(searchname);


        //请求page
        initMapParam(current, Constant.SIZE, "","","", shopsTypeId);

        initAdapter();

        initRefreshLayout();
    }


    private void initMapParam(int current, int size, String priceSort,String salesAmountSort,
                              String newSort,String shopsTypeId) {

        Map<String, String> productMap = new HashMap<>();


//        productMap.put("categoryId",categoryId);
        productMap.put("current", current + "");
        productMap.put("size", size + "");   //

            //商超分类的跳转过来的搜索结果
        if(typeShop ==1 ){
            //不需要参搜索名称
        }else {
            if(!TextUtils.isEmpty(searchname)){
                productMap.put("goodsName", searchname); //商品名字
            }
        }


        if(!TextUtils.isEmpty(categoryId)){
            productMap.put("categoryId", categoryId); //商超分类id
        }
        if(!TextUtils.isEmpty(priceSort)){
            productMap.put("goodsPriceSort", priceSort); //根据商品价格排序(desc,asc)
        }
        if(!TextUtils.isEmpty(salesAmountSort)){
            productMap.put("salesAmountSort", ""); //根据销量排序(desc,asc)
        }

        if(!TextUtils.isEmpty(newSort)){
            productMap.put("createTimeSort", priceSort); //根据新品排序(desc,asc)
        }

        if (!TextUtils.isEmpty(shopsTypeId)) {
            productMap.put("shopsTypeId", shopsTypeId); //shopsTypeId 模块搜索
        }

        mPresenter.getSearchPage(productMap);
    }

    List<IndexRecomBean.Data.Records> list = new ArrayList<>();

    //初始化adapter
    private void initAdapter() {

        //排序有问题
        searchAdapter = new SearchAdapter(mContext, list);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rvProduct.setLayoutManager(gridLayoutManager);

        rvProduct.setAdapter(searchAdapter);
//        searchAdapter.notifyDataSetChanged();

        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                GoodsInfoUtils.goodsInfo(mContext,searchAdapter.getData().get(position).getId(),searchAdapter.getData().get(position).getShopsTypeId());
//
            }
        });


    }

    //刷新
    private void initRefreshLayout() {

        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //id 需要传参过来
                current = 1;
                //需要清空数据再加
                list.clear();
                switch (state) {
                    case 0:
                        initMapParam(current, Constant.SIZE, "","","", shopsTypeId);
                        break;
                    case 1:
                        initMapParam(current, Constant.SIZE, "",salesAmountSort, "",shopsTypeId);
                        break;
                    case 2:
                        initMapParam(current, Constant.SIZE, priceSort, "","",shopsTypeId);
                    case 3:
                        initMapParam(current, Constant.SIZE, "", "",createTimeSort,shopsTypeId);
                        break;
                }


//                setSearchData(categoryId, currentSearchName, current, Constant.SIZE);

            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                current += 1;
                LogUtils.v("ruby--", current + "");
                switch (state) {
                    case 0:
                        initMapParam(current, Constant.SIZE, "","","", shopsTypeId);
                        break;
                    case 1:
                        initMapParam(current, Constant.SIZE, "",salesAmountSort, "",shopsTypeId);
                        break;
                    case 2:
                        initMapParam(current, Constant.SIZE, priceSort, "","",shopsTypeId);
                    case 3:
                        initMapParam(current, Constant.SIZE, "", "",createTimeSort,shopsTypeId);
                        break;
                }
//                setSearchData(categoryId, currentSearchName, current, Constant.SIZE);

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    boolean isAddFooterView = true;

    @Override
    public void getSearchPage(IndexRecomBean bean) {
        stopRefresh(smartrefreshlayout);

        if (bean.getData().getRecords().size() > 0) {
            llLoadingData.setVisibility(View.VISIBLE);
            llLoadingNoData.setVisibility(View.GONE);
            for (int i = 0; i < bean.getData().getRecords().size(); i++) {
                //添加集合中banner的数据
                list.add(bean.getData().getRecords().get(i));
            }
            if (current * Constant.SIZE > bean.getData().getTotal()) {
                smartrefreshlayout.setEnableLoadMore(false);

                if (isAddFooterView) {
                    View inflate = Global.inflate(R.layout.loadmore_addfooter_layout);
                    inflate.findViewById(R.id.tv_no_more).setBackgroundColor(getResources().getColor(R.color.color_f6f6f6));
                    searchAdapter.addFooterView(inflate);
                    isAddFooterView = false;
                }

            } else {
                isAddFooterView = true;
                searchAdapter.removeAllFooterView();
                smartrefreshlayout.setEnableLoadMore(true);

            }
            searchAdapter.notifyDataSetChanged();
        } else {
            if (list.isEmpty()) {
//                showEmptyView("暂无数据");
                llLoadingData.setVisibility(View.GONE);
                llLoadingNoData.setVisibility(View.VISIBLE);
            }

        }
    }
    private boolean isPriceSort = true; // true=1 false =2

    @OnClick({R.id.tv_ruby_synthesize, R.id.rt_ruby_sell, R.id.rt_ruby_price, R.id.tv_ruby_newsale})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //综合
            case R.id.tv_ruby_synthesize:

                list.clear();
                current = 1;
                state = 0;
                initMapParam(current, Constant.SIZE, "", "","",shopsTypeId);
                //请求数据
                setTextAndColor(R.color.home_new_color, R.color.black, R.color.black, R.color.black, R.drawable.icon_ruby_default);
                break;
                //销量
            case R.id.rt_ruby_sell:
                list.clear();
                state = 1;
                current = 1;
                salesAmountSort ="asc";
                initMapParam(current, Constant.SIZE, "", salesAmountSort,"",shopsTypeId);
                setTextAndColor(R.color.black, R.color.home_new_color, R.color.black, R.color.black, R.drawable.icon_ruby_default);
                break;
                //价格
            case R.id.rt_ruby_price:

                list.clear();
                current = 1;
                state = 2;
                if (isPriceSort) {
                    priceSort = "asc";
                    initMapParam(current, Constant.SIZE, priceSort, "","",shopsTypeId);
                    setTextAndColor(R.color.black, R.color.black, R.color.home_new_color, R.color.black, R.drawable.icon_ruby_up);
                    isPriceSort = false;
                } else {
                    priceSort = "desc";
                    initMapParam(current, Constant.SIZE, priceSort, "","",shopsTypeId);
                    setTextAndColor(R.color.black, R.color.black, R.color.home_new_color, R.color.black, R.drawable.icon_ruby_down);
                    isPriceSort = true;
                }
                break;
                //新品
            case R.id.tv_ruby_newsale:
                list.clear();
                state = 3;
                current = 1;
                createTimeSort = "asc";
                initMapParam(current, Constant.SIZE, "", createTimeSort,createTimeSort,shopsTypeId);
                setTextAndColor(R.color.black, R.color.black, R.color.black, R.color.home_new_color, R.drawable.icon_ruby_default);

                break;
        }
    }


    //设置不通的颜色和背景
    private void setTextAndColor(int p, int p2, int p3, int p4, int p5) {
        tvRubySynthesize.setTextColor(getResources().getColor(p));
        tvSellNumber.setTextColor(getResources().getColor(p2));
        tvRubyPrice.setTextColor(getResources().getColor(p3));
        tvRubyNewsale.setTextColor(getResources().getColor(p4));
        //价格和红豆
        ivRubyPrice.setBackground(getResources().getDrawable(p5));

    }
}
